<script setup>
let feedbackMessage = ref('');
import { ref } from 'vue';
import { setStorage, getStorage } from '../utils/storage';
import { sendGetRequestToLLM } from '../utils/llmService';

let ollamaAddress = ref('');

// models 列表数组，先尝试获取 storage 中的值，没有就默认为空
let models = ref([]);
getStorage('models').then((value) => {
  models.value = value || [];
});

let modelSelected = ref('');
getStorage('modelSelected').then((value) => {
  modelSelected.value = value || '';
});

const saveModel = async () => {
  await setStorage('modelSelected', modelSelected.value)
}

getStorage('ollamaAddress').then((value) => {
  ollamaAddress.value = value;
});

function checkAddressAccessibility(address) {
  return fetch(address)
    .then(response => response.ok)
    .catch(() => false);
}

async function saveAddress() {
  feedbackMessage.value = '请稍后...'
  const accessible = await checkAddressAccessibility(ollamaAddress.value);
  if (accessible) {
    await setStorage('ollamaAddress', ollamaAddress.value)
    feedbackMessage.value = '保存成功!';
    const res = await sendGetRequestToLLM('/api/tags')
    console.log(res.response);
    models.value = res.models.map(model => model.name);
    await setStorage('models', res.models.map(model => model.name))

  } else {
    feedbackMessage.value = '连接失败!';
  }
}
</script>

<template>
  <div class="min-h-screen bg-gray-100 flex justify-center">
    <div class="max-w-md p-4 bg-white rounded shadow-md">
      <h1 class="text-3xl font-bold mb-4">设置</h1>
      <form @submit.prevent="">
        <label for="ollamaAddress" class="block mb-2">Ollama 服务地址:</label>
        <input placeholder="请输入 ollama url" type="text" id="ollamaAddress" v-model="ollamaAddress"
          class="w-full p-2 text-sm text-gray-700 border rounded" />
        <button type="submit" class="mt-2 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          @click="saveAddress">提交地址</button>
        <p v-if="feedbackMessage" :class="feedbackMessage === '连接失败!' ? 'text-red-600' : 'text-green-600'">
          {{ feedbackMessage }}
        </p>
        <div class="w-64 mt-3">
          <select v-model="modelSelected" @change="saveModel" class="block w-full p-2 border rounded">
            <option value="" selected>输入地址后选一个模型</option>
            <option v-for="model in models"  :value="model" :key="model">
              {{ model }}
            </option>
          </select>
        </div>

      </form>
    </div>
  </div>
</template>

<style>
@tailwind base;
@tailwind components;
@tailwind utilities;
</style>
